// pages/answer/answer.js
const {
  getBarAndTitleHeight,
  stringify,
  parse,
  getStorage,
  jump,
  timer
} = require("../../utils/utils.js");
import {
  shareOptions
} from '../../utils/access';
import request from '../../utils/request'
const api = require("../../config/api");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    typeList: ['单选', '多选', '判断', '填空'],
    // 状态栏&标题栏高度
    ...getBarAndTitleHeight(true),
    QIndex: 1,
    totalNumber: 0,
    progress: 0,
    currentTitle: '我国目前首批设立了多少个垃圾分类重点城市？',
    question: null,
    isTest: null,
    progressValue: 10,
    hours: '0' + 0, // 时
    minute: '0' + 0, // 分
    second: '0' + 0 // 秒
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      isTest: Number(options.isTest),
      ...getBarAndTitleHeight(),
    });
    if (options.detail) {
      this.setData({
        detail: parse(options.detail)
      })
    } else {
      this.setData({
        detail: options
      })
    }
    if (options.question) {
      let question = parse(options.question)
      this.setData({
        question,
        totalNumber: question.length,
        progressValue: 1 / question.length * 100,
        isTask: 0,
      })
    } else if (options.taskId) { //任务答题
      this.getTaskTenQuestion(options.taskId)
    } else if (this.data.isTest === 1) { //每日一答
      this.getTenQuestion()
    }
  },
  //任务 获取随机10道题
  async getTaskTenQuestion(taskId) {
    const res = await request.get(api.getTenQuestion, {
      taskId
    })
    console.log('tenQuestion', res, res?.data?.map(item => item.answer));
    this.setData({
      question: res?.data,
      totalNumber: res?.data?.length,
      isTask: 1,
      taskId,
      progressValue: 1 / res?.data?.length * 100,
    })
  },
  /**
   * 每日一答获取随机10道题
   */
  async getTenQuestion() {
    const res = await request.get(api.testList, null, {
      loading: false
    })
    if (res.httpStatus === 200) {
      const question = res?.data?.data || []
      console.log('quick answer: ', question.map(m => m.answer))
      timer(this)
      this.setData({
        question,
        detail: {
          questionData: question,
          time: res?.msg
        },
        totalNumber: question.length,
        progressValue: 1 / question.length * 100,
        isTask: 0,
      })
    }
  },

  /**
   * 选择答案
   * @param {*} e 
   */
  submit(e) {
    if (this.loading) return
    this.loading = true
    let {
      QIndex,
      totalNumber,
      question,
      detail: {
        questionData
      }
    } = this.data
    if (this.data.isTest) {
      if (!questionData[QIndex - 1]['option' + e.currentTarget.dataset.value]) {
        this.loading = false
        return
      }
    } else {
      if (!question[QIndex - 1]['option' + e.currentTarget.dataset.value]) {
        this.loading = false
        return
      }
    }
    question[QIndex - 1]['myAnswer'] = e.currentTarget.dataset.value
    this.setData({
      question
    })
    setTimeout(() => {
      if (QIndex < totalNumber) {
        QIndex++
        this.setData({
          QIndex
        })
        if (QIndex === totalNumber) {
          this.setData({
            progressValue: 100
          })
        } else {
          this.setData({
            progressValue: QIndex / totalNumber * 100
          })
        }
        this.loading = false
      } else {
        console.log('question', question);
        this.submitMyAnswer(question, 1)
        this.setData({
          QIndex
        })
      }
    }, 500)
  },
  //提交答案
  async submitMyAnswer(question, isSubmit) {
    clearInterval(this.timerInterval)
    let {
      isTask,
      taskId,
      detail,
      isTest
    } = this.data
    let arr = []
    question.map((item) => {
      let obj = {
        id: item.id,
        type: item.type,
        usersAnswer: item.myAnswer ? item.myAnswer : ''
      }
      arr.push(obj)
    })
    const userId = getStorage("userId")
    let params = {
      isSubmit,
      isTask: isTest ? 2 : isTask,
      userId,
      taskId: taskId ? taskId : 0,
      studyQuestionRecordDTOList: arr
    }
    let url = ''
    if(this.data.isTest===1){
      url = api.submitAnswerEveryDay
      params.time = this.data.detail.time
    }else{
      url = api.submitAnswer
    }
    let result = await request.post(url, params)
    console.log('result', result);
    if (isSubmit == 0) {
      wx.navigateBack({
        delta: 1,
        // complete: ()=>{
        //   this.loading = false
        // }
      })
    } else {
      wx.redirectTo({
        url: `/pages/result/result?isTest=${isTest}&detail=${stringify(detail)}&result=${stringify(result.data)}&taskId=${taskId?taskId:0}`,
        // complete: ()=>{
        //   this.loading = false
        // }
      })
    }
  },

  //放弃答题
  giveUpAnswer() {
    if (this.loading) return
    this.modal.show()
  },
  //弹窗取消
  modalCancel() {
    this.modal.hide()
  },
  // 弹窗确定
  modalConfirm() {
    if(this.loading) return 
    this.loading = true
    this.submitMyAnswer(this.data.question, 1)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.modal = this.selectComponent('#modal')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loading = false
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearInterval(this.timerInterval)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  // 用户点击右上角分享
  onShareAppMessage(e) {
    if(this.data.isTest===1){
      const userId = getStorage('userId') || ''
      return shareOptions('default', e, '全国垃圾分类答题测试', `/pages/answerHome/answerHome?inviteData=${userId}`, 'https://image-classify.daieco.com/kejian-quanzi/TlHkdrPLJ0dd1a05ff9659bbd2311b67642b30830074.png')
    }else{
      return shareOptions('default',e)
    }
  },
})